package com.huitone.gddw.controller.worktable.paramconfigmanage;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.common.excel.CreateExcel;
import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.dao.entity.UserRouteRule;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.IUserRouteRuleService;
import com.huitone.gddw.service.dto.UserRouteRuleDTO;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 号段路由规则 控制器
 * @author wuluodan
 *
 */
@Controller
@RequestMapping(value="userRouteRule")
public class UserRouteRuleController extends CommonController {

	private final static Logger LOGGER = Logger.getLogger(UserRouteRuleController.class);
	
	@Autowired
	private IUserRouteRuleService userRouteRuleService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return QueryPage
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<UserRouteRuleDTO> query(QueryPage<UserRouteRule> page, HttpServletRequest request) {
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询号段路由规则";
		Map<String, Object> params = new HashMap<String, Object>();
		String province = request.getParameter("province");
		String mobilCorp = request.getParameter("mobilCorp");
		String sectionNo = request.getParameter("sectionNo");
		String status = request.getParameter("status");
		params.put("province", province);
		params.put("mobilCorp", mobilCorp);
		params.put("sectionNo", sectionNo);
		params.put("status", status);
		page.setParams(params);
		QueryPage<UserRouteRuleDTO> result = null;
		try {
			result = userRouteRuleService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询号段路由规则信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}
	
	/**
	 * 更改状态
	 * @param ruleId 规则ID
	 * @param status 更改后状态
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String ruleId, String status) {
		try {
			UserRouteRule entity = userRouteRuleService.selectByPrimaryKey(ruleId);
			entity.setStatus(status);
			userRouteRuleService.changeStatus(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改号段路由规则状态过程中出现异常：" + e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 修改页面数据准备
	 * @param ruleId 规则ID
	 * @return UserRouteRuleDTO
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public UserRouteRuleDTO toUpdate(String ruleId) {
		try {
			UserRouteRuleDTO entity = userRouteRuleService.toUpdate(ruleId);
			return entity;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new UserRouteRuleDTO();
		}
	}
	
	/**
	 * 保存
	 * @param entity UserRouteRule
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(UserRouteRule entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]添加号段路由规则";
		boolean isSuccess = true;
		String msg;
		try {
			UserRouteRule userRouteRule = userRouteRuleService.selectBySectionNo(entity.getSectionNo());
			if(userRouteRule!=null){
				return new Message(false, "该号段路由规则已存在！");
			}
			userRouteRuleService.save(entity);
			msg = "保存成功！";
		} catch (Exception e) {
			LOGGER.error("保存号段路由规则信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "保存失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 更新
	 * @param entity UserRouteRule
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(UserRouteRule entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改号段路由规则";
		boolean isSuccess = true;
		String msg;
		try {
			UserRouteRule userRouteRule = userRouteRuleService.selectByPrimaryKey(entity.getRuleId());
			userRouteRule.setRuleName(entity.getRuleName());
			userRouteRule.setSectionNo(entity.getSectionNo());
			userRouteRule.setProvince(entity.getProvince());
			userRouteRule.setMobilCorp(entity.getMobilCorp());
			userRouteRule.setStatus(entity.getStatus());
			userRouteRule.setDesc(entity.getDesc());
			userRouteRuleService.update(userRouteRule);
			msg = "修改成功！";
		} catch (Exception e) {
			LOGGER.error("修改号段路由规则信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除
	 * @param ruleId 规则ID
	 * @return Message
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String ruleId) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除号段路由规则";
		boolean isSuccess = true;
		String msg;
		try {
			userRouteRuleService.delete(ruleId);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除号段路由规则信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 导出 Excel
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/out-excel", method=RequestMethod.POST)
	public void outExcel(HttpServletRequest request, HttpServletResponse response) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "号段路由规则信息表";
		
		Map<String, Object> params = new HashMap<String, Object>();
		for (Object name : request.getParameterMap().keySet()) {
			params.put(name.toString(), request.getParameter(name.toString()));
		}
		
		List<UserRouteRuleDTO> list = userRouteRuleService.getRecord(params);
		if (null == list || 0 == list.size()) {
			list.add(new UserRouteRuleDTO());
		}
		
		HSSFWorkbook wb = (HSSFWorkbook)CreateExcel
				.getInstance()
				.CreateNewExcelNoTemplate(fileName, list).getWorkbook();
		OutputStream fOut = null;
		try {
			fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
			response.reset();
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename="+fileName+sdf.format(new Date())+".xls");
			fOut = response.getOutputStream();
			wb.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {

			}
		}
	}
	
}
